﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using com.tiyma.model;

namespace com.tiyma.common
{
    public class CookieManager
    {
        static readonly string Domain = AppConfig.Domain;

        const string VifCode = "vc";
        const string LoginInfo = "ll";
        const string bookClick = "bookClick";
        const string chapter = "c";
        /// <summary>
        /// 章节阅读cookie
        /// </summary>
        const string read_chapter_cookie = "tiyma_rcb_p_c";



        /// <summary>
        /// 设置验证码
        /// </summary>
        /// <param name="cookieValue"></param>
        public static void SetVifCode(string cookieValue)
        {
            HttpCookie cookie = new HttpCookie(VifCode);

            if (!string.IsNullOrEmpty(Domain))
                cookie.Domain = Domain;

            cookie.Value = cookieValue;

            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 设置用户退出登录信息
        /// </summary>
        public static void SetUserLoginOut()
        {
            HttpCookie curCookie = null;

            if (String.IsNullOrEmpty(GetLoginUser()))
            {
                curCookie = new HttpCookie(LoginInfo);
            }
            else
            {
                curCookie = HttpContext.Current.Request.Cookies[LoginInfo];
            }
            if (!string.IsNullOrEmpty(AppConfig.Domain))
                curCookie.Domain = AppConfig.Domain;
            curCookie.Expires = DateTime.Now.AddDays(-1);
            HttpContext.Current.Response.Cookies.Add(curCookie);

        }


        /// <summary>
        /// 获取设置的验证码
        /// </summary>
        /// <returns></returns>
        public static string GetVifCode()
        {

            if (HttpContext.Current.Request.Cookies[VifCode] != null)
                return HttpContext.Current.Request.Cookies[VifCode].Value;

            return string.Empty;
        }

        /// <summary>
        /// 设置登陆信息
        /// </summary>
        /// <param name="cookieValue"></param>
        public static void SetLoginUserInfo(string cookieValue)
        {
            HttpCookie cookie = new HttpCookie(LoginInfo);

            if (!string.IsNullOrEmpty(Domain))
                cookie.Domain = Domain;

            cookie.Value = cookieValue;


            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 设置书籍点击次数
        /// </summary>
        /// <param name="i_book_id"></param>
        public static void SetBookReadCount(long i_book_id)
        {
            HttpCookie cookie = new HttpCookie(bookClick);

            if (!string.IsNullOrEmpty(Domain))
                cookie.Domain = Domain;

            cookie.Value = i_book_id.ToString();

            cookie.Expires = DateTime.Now.AddMinutes(3);


            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 判断是否是要加书籍点击 true 是需要更新点击 false不需要
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <returns></returns>
        public static bool GetBookReadCount(long i_book_id)
        {
            if (HttpContext.Current.Request.Cookies[bookClick] != null)
            {
                string t_book_click_cookie = HttpContext.Current.Request.Cookies[bookClick].Value;
                if (t_book_click_cookie.IndexOf(i_book_id.ToString()) > -1)
                    return false;
            }
            SetBookReadCount(i_book_id);
            return true;
        }


        /// <summary>
        /// 获取登陆用户的登陆名
        /// </summary>
        /// <returns></returns>
        public static string GetLoginUser()
        {
            if (HttpContext.Current.Request.Cookies[LoginInfo] != null)
                return HttpContext.Current.Request.Cookies[LoginInfo].Value;

            return string.Empty;
        }

        /// <summary>
        /// 设置最近阅读
        /// </summary>
        /// <param name="i_chapter"></param>
        public static void SetCurReadBook(ChapterInfo i_chapter)
        {
            try
            {
                string t_cur_read = GetBookReadCookie();
                //bookId*bookName*chapterId*chapterName$*isDownLoad
                StringBuilder t_sb = new StringBuilder();
                t_sb.AppendFormat("{0}*{1}*{2}*{3}*{4}*{5}$",
                    i_chapter.BookId,
                    HttpUtility.UrlEncode(i_chapter.BookName),
                    i_chapter.ChapterId,
                    HttpUtility.UrlEncode(i_chapter.ChapterName),
                    i_chapter.SiteId,
                    i_chapter.IsDownLoad
                    );
                if (!string.IsNullOrEmpty(t_cur_read))
                {
                    string[] t_arr = t_cur_read.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                    if (t_arr != null && t_arr.Length > 0)
                    {
                        for (int index = 0; index < t_arr.Length; index++)
                        {
                            string[] t_arr_c = t_arr[index].Split(new char[] { '*' }, StringSplitOptions.None);

                            if (t_arr_c[0] != i_chapter.BookId.ToString())
                            {
                                t_sb.AppendFormat("{0}*{1}*{2}*{3}*{4}*{5}$",
                                  t_arr_c[0],
                                   t_arr_c[1],
                                   t_arr_c[2],
                                   t_arr_c[3],
                                   t_arr_c[4],
                                   t_arr_c[5]
                                  );
                            }
                            if (index == 3)
                                break;
                        }
                    }
                }

                HttpCookie cookie = new HttpCookie(read_chapter_cookie);

                if (!string.IsNullOrEmpty(Domain))
                    cookie.Domain = Domain;

                cookie.Value = t_sb.ToString();
                cookie.Expires = System.DateTime.Now.AddMonths(6);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
            catch (Exception ex)
            {
                LogHelper.Error("设置最近阅读信息失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 获取最近阅读列表
        /// </summary>
        /// <returns></returns>
        public static List<ChapterInfo> GetCurReadList()
        {
            List<ChapterInfo> t_list = null;
            try
            {
                string t_cur_read = GetBookReadCookie();
                //bookId*bookName*chapterId*chapterName*isDownLoad$
              
                if (!string.IsNullOrEmpty(t_cur_read))
                {
                    t_list = new List<ChapterInfo>();
                    ChapterInfo t_chapter = null;
                    string[] t_arr = t_cur_read.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
                    if (t_arr != null && t_arr.Length > 0)
                    {
                        for (int index = 0; index < t_arr.Length; index++)
                        {
                            string[] t_arr_c = t_arr[index].Split(new char[] { '*' }, StringSplitOptions.None);
                            if (t_arr_c != null && t_arr_c.Length == 6)
                            {
                                t_chapter = new ChapterInfo();
                                t_chapter.BookId = t_arr_c[0];
                                t_chapter.BookName = HttpUtility.UrlDecode(t_arr_c[1]);
                                t_chapter.ChapterId = t_arr_c[2];
                                t_chapter.ChapterName = HttpUtility.UrlDecode(t_arr_c[3]);
                                t_chapter.SiteId = string.IsNullOrEmpty(t_arr_c[4]) ? 0 : Convert.ToInt32(t_arr_c[4]);
                                t_chapter.IsDownLoad = string.IsNullOrEmpty(t_arr_c[5]) ? 0 : Convert.ToInt32(t_arr_c[5]);
                                t_list.Add(t_chapter);
                            }
                        }
                    }
                }

            }
            catch (Exception ex)
            {
                LogHelper.Error("获取最近阅读列表失败" + ex.ToString());
            }

            return t_list;
        }


      
        /// <summary>
        /// 设置章节阅读cookie 以便继续上次阅读
        /// </summary>
        /// <param name="i_book_id"></param>
        /// <param name="i_chapter_id"></param>
        public static void SetBookReadCookie( string i_book_name)
        {
            string t_cur_read = GetBookReadCookie();

            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0}", HttpUtility.UrlEncode(i_book_name)).Append("$");
            if (!string.IsNullOrEmpty(t_cur_read))
            {
                string[] t_arr = t_cur_read.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
    
                for (var index = 0; index <t_arr.Length; index++)
                {
                 
                    sb.AppendFormat("{0}", t_arr[index]);
                    sb.Append("$");

                    if (index ==20)
                        break;
                    
                }
            }

            HttpCookie cookie = new HttpCookie(read_chapter_cookie);

            if (!string.IsNullOrEmpty(Domain))
                cookie.Domain = Domain;

            cookie.Value = sb.ToString();
            cookie.Expires = System.DateTime.Now.AddMonths(6);


            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 删除最近阅读
        /// </summary>
        /// <param name="i_book_list"></param>
        public static void DeleteReadBook(List<string> i_book_list)
        {
            if(i_book_list==null ||i_book_list.Count<=0)
                return;
            string t_cur_read = GetBookReadCookie();

            StringBuilder sb = new StringBuilder();

            if (!string.IsNullOrEmpty(t_cur_read))
            {
                string[] t_arr = t_cur_read.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);

                for (var index = 0; index <t_arr.Length; index++)
                {
                    if (!i_book_list.Contains(HttpUtility.UrlDecode( t_arr[index])))
                    {
                        sb.AppendFormat("{0}", t_arr[index]);
                        sb.Append("$");
                    }

                }
            }

            HttpCookie cookie = new HttpCookie(read_chapter_cookie);

            if (!string.IsNullOrEmpty(Domain))
                cookie.Domain = Domain;

            cookie.Value = sb.ToString();
            cookie.Expires = System.DateTime.Now.AddMonths(6);
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        /// <summary>
        /// 获取章节阅读cookie 以便继续上次阅读
        /// </summary>
        /// <returns></returns>
        public static string GetBookReadCookie()
        {
            if (HttpContext.Current.Request.Cookies[read_chapter_cookie] != null)
                return HttpContext.Current.Request.Cookies[read_chapter_cookie].Value;

            return string.Empty;
        }


        /// <summary>
        /// 获取章节页cookie
        /// </summary>
        /// <returns></returns>
        public static string GetChapterCookie()
        {
            if (HttpContext.Current.Request.Cookies[chapter] != null)
                return HttpContext.Current.Request.Cookies[chapter].Value;

            return string.Empty;
        }

        /// <summary>
        /// 获取当前登录用户的id
        /// </summary>
        /// <returns></returns>
        public static long GetUserId()
        {
            string t_cur_user = GetLoginUser();
            if (string.IsNullOrEmpty(t_cur_user))
                return 0;

            string[] t_arr = t_cur_user.Split(new char[] { '$' }, StringSplitOptions.RemoveEmptyEntries);
            if (t_arr.Length != 2)
                return 0;
            long t_user_id = 0;
            if (!long.TryParse(t_arr[1].ToString(), out t_user_id))
                t_user_id = 0;
            return t_user_id;
        }
    }
}
